package com.ray.tool;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;

/**
 * 基于雪花算法的ID生成器 - 工具类
 *
 * @author LiaoYuXing-Ray
 * @version 1.0
 * @createDate 2023/9/7 19:48
 **/
public class RayIdWorker {

    // 开始时间戳（2023-09-07）
    private final static long twepoch = 1672444800000L;
    // 机器id所占的位数
    private final static long workerIdBits = 5L;
    // 数据标识id所占的位数
    private final static long datacenterIdBits = 5L;
    // 支持的最大机器id，结果是31（二进制：11111）
    private final static long maxWorkerId = ~(-1L << workerIdBits);
    // 支持的最大数据标识id，结果是31（二进制：11111）
    private final static long maxDatacenterId = ~(-1L << datacenterIdBits);
    // 序列在id中占的位数
    private final static long sequenceBits = 12L;
    // 机器ID向左移12位
    private final static long workerIdShift = sequenceBits;
    // 数据标识id向左移17位（12+5）
    private final static long datacenterIdShift = sequenceBits + workerIdBits;
    // 时间截向左移22位（5+5+12）
    private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    // 生成序列的掩码，这里为4095（二进制：111111111111）
    private final static long sequenceMask = ~(-1L << sequenceBits);
    // 工作机器ID(0~31)
    private final long workerId;
    // 数据中心ID(0~31)
    private final long datacenterId;
    // 毫秒内序列(0~4095)
    private long sequence = 0L;
    // 上次生成ID的时间截
    private long lastTimestamp = -1L;

    public RayIdWorker() {
        this.datacenterId = getDatacenterId(maxDatacenterId);
        this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    }

    /**
     * 构造方法
     *
     * @param workerId     工作机器ID(0~31)
     * @param datacenterId 数据中心ID(0~31)
     * @author LiaoYuXing-Ray 2023/9/7 20:03
     **/
    public RayIdWorker(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    /**
     * 获取下一个ID
     *
     * @return long ID
     * @author LiaoYuXing-Ray 2023/9/12 20:04
     **/
    public synchronized long nextId() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        if (lastTimestamp == timestamp) {
            // 当前毫秒内，则+1
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                // 当前毫秒内计数满了，则等待下一秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        // ID便宜组合生成最终ID，并返回ID
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
    }

    /**
     * 获取下一个ID
     *
     * @return long ID
     * @author LiaoYuXing-Ray 2023/9/12 20:04
     **/
    public synchronized String nextStringId() {
        return String.valueOf(this.nextId());
    }

    public static RayIdWorker getInstance() {
        return new RayIdWorker();
    }


    protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
        StringBuilder mpid = new StringBuilder();
        mpid.append(datacenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (!name.isEmpty()) {
            /*
             * get jvmPid 2023/9/12 20:09
             */
            mpid.append(name.split("@")[0]);
        }
        /*
         * Mac + PID 的 hashcode 获取16个低位 2023/9/12 20:10
         */
        return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    }

    /**
     * 获取数据标识id部分
     *
     * @param maxDatacenterId 支持的最大数据标识id，结果是31（二进制：11111）
     * @return long
     * @author LiaoYuXing-Ray 2023/9/12 20:11
     **/
    protected static long getDatacenterId(long maxDatacenterId) {
        long id = 0L;
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);

            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                if (mac != null && mac.length > 0) {
                    id = ((0x000000FF & (long) mac[mac.length - 1])
                            | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
                    id = id % (maxDatacenterId + 1);
                } else {
                    id = 1L;
                }
            }
        } catch (Exception e) {
            System.out.println("getDatacenterId：" + e.getMessage());
        }
        return id;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

//    /*
//    使用示例
//    public static void main(String[] args) {
//        RayIdWorker idWorker = RayIdWorker.getInstance();
//        for (int i = 0; i < 10; i++) {
//            System.out.println(idWorker.nextId());
//            System.out.println(idWorker.nextStringId());
//        }
//    }
//    */
}
